package com.decent.manager.system.auth.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.decent.common.entity.manager.SystemUser;
import com.decent.manager.system.auth.jwt.JwtPayLoad;
import com.decent.manager.system.auth.service.CleanAuthService;
import com.decent.manager.system.auth.vo.LoginUser;
import com.decent.manager.system.cache.LoginUserCache;
import com.decent.manager.system.dao.SystemUserRoleDao;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * 清空认证管理实现
 *
 * @className: CleanAuthServiceImpl
 * @author: wangyan
 * @date: 2022/4/16
 **/
@Service
public class CleanAuthServiceImpl implements CleanAuthService {
    @Resource
    private SystemUserRoleDao systemUserRoleDao;
    @Resource
    private LoginUserCache<LoginUser> loginUserCache;

    /**
     * 清空用户缓存的登录信息
     *
     * @param user 用户
     */
    @Override
    public void clearLoginUserCache(SystemUser user) {
        loginUserCache.clearUser(loginUserCache.getCacheKeyPostfix(user));
    }

    /**
     * 按角色清空用户缓存的登录信息
     *
     * @param roleId 角色id
     */
    @Override
    public void clearLoginUserCacheByRole(Long roleId) {
        List<SystemUser> users = systemUserRoleDao.queryUsers(roleId);
        users.forEach(user -> loginUserCache.clearUser(loginUserCache.getCacheKeyPostfix(user)));
    }

    /**
     * 清空当前用户缓存的登录信息
     *
     * @param jwtPayLoad 当前信息
     */
    @Override
    public void clearCurrentUser(JwtPayLoad jwtPayLoad) {
        //获取缓存的用户
        LoginUser cacheObject = loginUserCache.get(jwtPayLoad.getUuid());
        //如果缓存的用户存在，清除会话，否则表示该会话信息已失效，不执行任何操作
        if (ObjectUtil.isNotEmpty(cacheObject)) {
            //清除登录会话
            loginUserCache.remove(jwtPayLoad.getUuid());
        }
    }
}
